var $outer;
let stompClient = null;
let fullScreenLoading;

var $placeAudio;

Vue.component('my-card', {
  // data: function () {
  //   return {
  //     xCoordinate: -1,
  //     yCoordinate: -1,
  //   }
  // },
  computed: {
    // 在组件内使用计算属性计算样式
    // computeClassObject: function () {
    //   return (this.xCoordinate + this.yCoordinate) % 2 === 0 ? 'color-red' : '';
    // }
  },

  template: '<div></div>'
});
var app = new Vue({
  el: "#app",
  data: function () {
    return {
      rowTotal: 19,
      colTotal: 19,
      layoutData: [],

      FLAG_Z_MY: 1,
      FLAG_Z_OTH: 2,
      oth_nick: '',

      fullscreenLoading: false,

      msgToSend: '',
      CAN_SEND_MSG: true,
      GAME_ID: '',
      USER_ID: '',
      IS_CREATOR: false,

      CAN_I_PLACE: false,

      CAN_CHESS_MOD: false,

      mn: '',
      mw: 0,
      mi: 0,

      on: '等待用户加入...',
      ow: 0,
      oi: 0,

      roundNo: 0,

      // 游戏状态：0等待加入，1用户加入未开始，2游戏进行中
      GAME_STATE: -1,
      //  ws相关
      isAlive: false,

      // API_BASE_URL: 'http://127.0.0.1:12345',
      API_BASE_URL: 'http://106.14.115.245:12345',

      showWinAnimationFlag: false,

      showHeaderFlag: true,

      lastChess: {
        x: -1,
        y: -1
      },
      lastIsMe: false,
      othAI: false,

    }
  },
  mounted: function () {

    $outer = $("#outer");
    $placeAudio = document.getElementById("place-human");
    // this.layoutData[10]
    // loop();
    this.initGame();
    this.stopSound();
  },
  computed: {
    colorObj: function (m, n) {
      return {
        'color-red': m % 2 === 0,
        'color-green': m % 2 === 0,
        'color-blue': m % 5 === 0,
      }
    },

    classObject: function () {
      return {
        'active-nick': this.CAN_I_PLACE,
      }
    },
    classObject2: function () {
      return {
        'active-me-chess': !this.CAN_I_PLACE && this.GAME_STATE === 2,
      }
    },
    animationZIndex: function () {
      return {
        'lower': !this.showWinAnimationFlag
      }
    },
    hightlightCard: function () {
      return {
        'highlight-card': this.GAME_STATE === 2 && this.CAN_I_PLACE
      }
    },
    hightlightCard2: function () {
      return {
        'highlight-card': this.GAME_STATE === 2 && !this.CAN_I_PLACE
      }
    }
  },
  methods: {

    hideHeader() {
      this.showHeaderFlag = false;
      $("#header").slideUp(1000);
    },
    showHeader() {
      this.showHeaderFlag = true;
      $("#header").slideDown(1000);
    },
    showWinAnimation() {
      this.showWinAnimationFlag = true;
      loop();
    },
    stopWinAnimation() {
      this.showWinAnimationFlag = false;
      stopAnimation();
    },
    initGame() {
      this.openFullScreenLoading("游戏加载中，请稍候...");
      const gameId = getQueryString("gameId");
      const userId = getQueryString("userId");
      this.GAME_ID = gameId;
      this.USER_ID = userId;
      let that = this;
      let socket = new SockJS(
          that.API_BASE_URL + '/gmkServer?gameId=' + gameId + "&userId="
          + userId);
      stompClient = Stomp.over(socket);
      stompClient.connect({}, function () {
        that.isAlive = true;
        // 个人消息
        stompClient.subscribe('/user/queue/myself', function (response) {
          that.displayMyMessage(JSON.parse(response.body));
        });

        that.closeFullScreenLoading();
      }, function (message) {
        that.closeFullScreenLoading();
        that.isAlive = false;
        that.showSimpleAutoHideTopMessage('error', "失去与服务器的连接...");
      });
    },

    sendMyMessage: function (msgObj) {
      this.sendMessage("/app/gmk/opt/" + this.GAME_ID + "/" + this.USER_ID,
          msgObj);
    },

    sendMessage: function (url, obj) {
      if (this.isAlive) {
        stompClient.send(url, {}, JSON.stringify(obj));
      } else {
        this.$notify.error({
          title: '连接错误',
          message: '失去与服务器的连接，请刷新页面重试',
          duration: 0
        });
      }
    },
    displayFun: function (funNo, obj) {
      switch (funNo) {
        case 101: // 打开落子
          this.CAN_I_PLACE = true;
          this.GAME_STATE = 2;
          break;
        case 201: // 修改棋子状态, obj chessman
          this.CAN_CHESS_MOD = true;
          this.modChessDirectly(obj.point.x, obj.point.y,
              obj.p.userId === this.USER_ID, true);
          break;
        case 202: // 重置单个棋子
          this.CAN_CHESS_MOD = true;
          this.modChessDirectly(obj.point.x, obj.point.y,
              false, false);
          break;
        case 301: // 重置布局
                  // TODO 修改另一个用户的昵称
          this.GAME_STATE = 1;
          if (obj != null && obj === this.USER_ID) {
            this.IS_CREATOR = true;
          } else {
            this.IS_CREATOR = false;
          }
          this.resetChess();
          break;
        case 401: // 开始游戏
          this.resetChess();
          this.GAME_STATE = 2;

          this.setPlayerInfo(obj);
          this.othAI = obj.ai;
          if (obj.creatorId != null && obj.creatorId === this.USER_ID) {
            this.IS_CREATOR = true;
          } else {
            this.IS_CREATOR = false;
          }

          break;
        case 501: // 回合结束
          this.CAN_I_PLACE = false;
          this.GAME_STATE = 1;
          this.CAN_CHESS_MOD = false;
          // if (obj.winUserId != null && obj.winUserId === this.USER_ID) {
          //   this.showWinAnimation();
          // }
          this.setPlayerInfo(obj);

          break;

        case 601: //用户加入 obj : Player
          this.on = obj.nick;
          break;
        default:
          break;
      }
    },

    setPlayerInfo(obj) {
      this.mn = obj.meNick;
      this.mw = obj.meWinRoundCount;
      this.mi = obj.meIntegral;
      this.on = obj.othNick;
      this.ow = obj.othWinRoundCount;
      this.oi = obj.othIntegral;
      this.roundNo = obj.roundNo;
    },
    resetChess: function () {
      $.each($(".chessman-out"), function (idx, obj) {
        obj.setAttribute("data-z", 0);
        $(obj).find(".chessman:first-child").removeClass("p1 p2 p3");
      });
      this.resetLastChess();
    },
    resetLastChess() {
      this.lastChess = {
        x: -1, y: -1
      }
    },

    displayMyMessage: function (data) {
      if (!data.success) {
        this.showSimpleAutoHideTopMessage("error", data.message);
        return;
      }
      let gmkResp = data.data;
      console.log(gmkResp);
      // 功能编号使用data1
      this.displayFun(gmkResp.funNo, gmkResp.data1);
      const responseType = gmkResp.responseType;
      switch (responseType) {
        case 0:
          break;
        case 1:
          this.showTopMessage(gmkResp.data0);
          break;
        case 2:
          this.showRightMessage(gmkResp.data0);
          break;
        case 3:
          this.showLeftMessage(gmkResp.data0);
          break;

        case 11: // 显示对话框
          this.showConfirmDialog(gmkResp.data0);
          break;
        default:
          this.showSimpleAutoHideTopMessage("warning", "非法消息类型");
          return;
      }
    },

    startRound() {
      let that = this;
      $.get({
        url: this.API_BASE_URL + '/api/gomoku/start?gameId='
            + this.GAME_ID,
        dataType: 'json',
        success: function (res) {
          if (!res.success) {
            that.showSimpleAutoHideTopMessage("error", res.message);
          }
        }
      });
    },
    resetRound() {
      let that = this;
      $.get({
        url: this.API_BASE_URL + '/api/gomoku/reset?gameId=' + this.GAME_ID
            + "&userId=" + this.USER_ID,
        dataType: 'json',
        success: function (res) {
          if (!res.success) {
            that.showSimpleAutoHideTopMessage("error", res.message);
          }
        }
      });
    },
    surrenderRound() {
      const that = this;
      this.$confirm('此操作是下下之策，您可以发送消息或发送悔棋以求对方给个机会, 是否继续投降?', '提示', {
        confirmButtonText: '偏要认输',
        cancelButtonText: '等待机会',
        type: 'warning'
      }).then(() => {
        $.get({
          url: this.API_BASE_URL + '/api/gomoku/surrender?gameId='
              + this.GAME_ID
              + "&userId=" + this.USER_ID,
          dataType: 'json',
          success: function (res) {
            if (!res.success) {
              that.showSimpleAutoHideTopMessage("error", res.message);
            }
          }
        });
      }).catch(() => {
        this.$message({
          type: 'success',
          message: '坚持就是胜利，不行卖个萌'
        });
      });
    },

    begForChance() {
      const that = this;
      this.$confirm('悔棋操作需要对手同意，是否发送请求?', '提示', {
        confirmButtonText: '发送请求',
        cancelButtonText: '再考虑一下',
        type: 'warning'
      }).then(() => {
        $.get({
          url: this.API_BASE_URL + '/api/gomoku/withdrawReq?gameId='
              + this.GAME_ID
              + "&userId=" + this.USER_ID,
          dataType: 'json',
          success: function (res) {
            if (!res.success) {
              that.showSimpleAutoHideTopMessage("error", res.message);
            }
          }
        });
      }).catch(() => {
        this.$message({
          type: 'success',
          message: '坚持就是胜利，不行卖个萌'
        });
      });
    },
    sendMsgToPlayer() {
      let that = this;
      if (this.CAN_SEND_MSG) {
        this.CAN_SEND_MSG = false;
        setTimeout(function () {
          that.CAN_SEND_MSG = true;
        }, 2000);
        this.sendMyMessage({
          requestNo: 201,
          body: this.msgToSend,
        });
        this.msgToSend = '';
        this.showQuickSimpleAutoHideTopMessage("success", "发送成功", 1000);

      } else {
        this.showQuickSimpleAutoHideTopMessage("warning", "您的发送频率过快，请慢一点",
            1000);
      }
    },

    displayLast() {
      console.log("12321312312");
      if (this.lastChess.x === -1) {
        this.showSimpleAutoHideTopMessage('warning', '当前不在游戏中或没有落子信息！');
        return;
      }
      const that = this;
      const x = this.lastChess.x;
      const y = this.lastChess.y;
      $.each($(".chessman-out"), function (idx, obj) {
        let m = parseInt(obj.getAttribute("data-x"));
        let n = parseInt(obj.getAttribute("data-y"));
        if (x === m && y === n) {
          let $t = $(obj).find(".chessman:first-child");
          let hasP1 = $t.hasClass("p1");
          $t.removeClass("p1");
          $t.removeClass("p2");
          // $t.addClass("p3");
          $t.addClass("dot");

          if (hasP1) {
            setTimeout(function () {
              $t.removeClass("dot");
              $t.addClass("p1");
            }, 3000);
          } else {
            setTimeout(function () {
              $t.removeClass("dot");
              $t.addClass("p2");
            }, 3000);
          }
          return false;
        }
      });
    },

    modChessDirectly(x, y, isMe, add) {
      console.log(x, y, isMe, add);
      const that = this;
      this.lastChess = {x, y};
      if (this.CAN_CHESS_MOD) {
        $.each($(".chessman-out"), function (idx, obj) {
          let m = parseInt(obj.getAttribute("data-x"));
          let n = parseInt(obj.getAttribute("data-y"));
          if (x === m && y === n) {
            let z = parseInt(obj.getAttribute("data-z"));
            let $t = $(obj).find(".chessman:first-child");
            if (add) {
              if (isMe) {
                that.lastIsMe = true;
                that.playSound();
                $t.addClass("p1");
                obj.setAttribute("data-z", 1);
                return false;
              } else {
                that.lastIsMe = false;
                if (!that.othAI) {
                  that.playSound();
                }
                obj.setAttribute("data-z", 2);
                $t.addClass("p3");
                setTimeout(function () {
                  $t.removeClass("p3");
                  $t.addClass("p2");
                }, 1300);
                return false;
              }
            } else {
              $t.removeClass("p1 p2 p3 dot");
              obj.setAttribute("data-z", 0);
            }
            return false;
          }

        });
      }
    },

    playSound() {
      $placeAudio.currentTime = 0;
      $placeAudio.play();
      const that = this;
      setTimeout(function () {
        that.stopSound();
      }, 1000)
    },
    stopSound() {
      $placeAudio.pause();
    },
    displayThis(m, n) {
      return m % 2 === 0;
    },

    getMyColor(m, n) {
      const sum = (m + n + 1);
      return sum % 2 === 0 ? '' : 'color-grey';
      // if (sum % 2 === 0) {
      //   return 'color-red';
      // } else if (sum % 3 === 0) {
      //   return 'color-green';
      // } else if (sum % 5 === 0) {
      //   return 'color-black';
      // } else {
      //   return 'color-blue';
      // }
    },
    modChess(m, n) {
      if (!this.CAN_I_PLACE) {
        this.showSimpleAutoHideTopMessage("warning", "当前不可以落子");
        return;
      }
      let that = this;
      const f1 = this.FLAG_Z_MY;
      const f2 = this.FLAG_Z_OTH;
      $.each($(".chessman-out"), function (idx, obj) {
        let x = parseInt(obj.getAttribute("data-x"));
        let y = parseInt(obj.getAttribute("data-y"));
        if (x === m && y === n) {
          let z = parseInt(obj.getAttribute("data-z"));
          if (z === f1 || z === f2) {
            that.showSimpleAutoHideTopMessage("warning", "这个位置已经有棋子了哦");
            return false;
          }
          that.CAN_I_PLACE = false;
          that.CAN_CHESS_MOD = false;
          if (z === 0) {
            that.sendMyMessage({
              x: x,
              y: y,
              requestNo: 101
            });
            // $(obj).addClass("p1");
            // obj.setAttribute("data-z", 1);
            return false;
          }
          return false;
        }
      });
    },

    showTopMessage: function (obj) {
      console.log(obj);
      return (this.$message({
        type: obj.type,
        message: obj.content,
        duration: obj.duration,
        autoClose: obj.autoClose,
        showClose: obj.showClose,
        dangerouslyUseHTMLString: true,
      }));
    },

    showSimpleAutoHideTopMessage(type, text) {
      this.showTopMessage({
        type: type,
        content: text,
        duration: 2000,
        autoClose: true,
        showClose: true,
        dangerouslyUseHTMLString: true,
      })
    },

    showQuickSimpleAutoHideTopMessage(type, text, time) {
      this.showTopMessage({
        type: type,
        content: text,
        autoClose: true,
        showClose: false,
        duration: time
      })
    },

    showRightMessage: function (msgObj) {
      return (this.$notify({
        title: msgObj.title,
        message: msgObj.content,
        type: msgObj.type,
        duration: msgObj.duration,
        autoClose: msgObj.autoClose,
        showClose: msgObj.showClose,
        dangerouslyUseHTMLString: true,
      }));
    },

    showLeftMessage: function (msgObj) {
      return (this.$notify({
        title: msgObj.title,
        message: msgObj.content,
        type: msgObj.type,
        duration: msgObj.duration,
        autoClose: msgObj.autoClose,
        showClose: msgObj.showClose,
        dangerouslyUseHTMLString: true,
        position: 'top-left'
      }));
    },

    showConfirmDialog: function (msgObj) {
      const that = this;
      this.$confirm(msgObj.body, msgObj.title, {
        confirmButtonText: msgObj.confirmText,
        cancelButtonText: msgObj.cancelText,
        type: msgObj.type
      }).then(() => {
        let uri = msgObj.biz;
        if (uri.indexOf("?") > 0) {
          uri = uri + "&agree=true"
        }
        that.CAN_I_PLACE = false;
        that.CAN_CHESS_MOD = false;
        $.get({
          url: this.API_BASE_URL + '/api/gomoku/' + uri,
          dataType: 'json',
          success: function (res) {
            if (!res.success) {
              that.showSimpleAutoHideTopMessage("error", res.message);
            }
          }
        });
      }).catch(() => {
        let uri = msgObj.biz;
        if (uri.indexOf("?") > 0) {
          uri = uri + "&agree=false"
        }
        $.get({
          url: this.API_BASE_URL + '/api/gomoku/' + uri,
          dataType: 'json',
          success: function (res) {
            if (!res.success) {
              that.showSimpleAutoHideTopMessage("error", res.message);
            }
          }
        });
      });
    },

    openFullScreenLoading: function (text) {
      fullScreenLoading = this.$loading({
        lock: true,
        text: text,
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.7)'
      });
    },

    closeFullScreenLoading: function () {
      fullScreenLoading.close();
    },

    resetForm() {
      Object.assign(this.form, this.$options.data().form)
    },

  }

});